Spring Security 기본 사용자 추가 및 테스트

✒️ 2025-05-28 14:13 내용 수정


Spring Security 기본 사용자 추가 및 테스트


  1. 새 프로젝트를 만들고, dependency 설정에서 Spring Security를 체크한다.
    • MyBatis와 DB 연결 관련 설정을 체크하고 관련 설정을 안 해주면 에러가 나기 때문에 DB 연결 설정 부분을 제거하고 테스트한다.
    • IDE 프로젝트 외에도 https://start.spring.io/ 에서 필요한 Dependencies를 모두 적용한 프로젝트 파일을 생성하여 IDE에서 실행하는 것도 있다.

spring security 1.png

  1. application.properties이나 application.yml에서 서버 설정과 Spring Security 설정 중 사용자의 username, password, roles를 지정한다.
    • 로그인 페이지에서 이 파일에 지정한 name과 password로 로그인을 하면 된다.
# properties file
# Server port 
server.port=9090 

# Spring Security 설정 
spring.security.user.name=user 
spring.security.user.password=password 
spring.security.user.roles=USER
# yml file
# Server port
server:
  port: 9090
  
# Spring Security 설정
spring:
  security:
    user:
      name: user
      password: password
      roles: USER
  1. TestController를 생성하여 기본 요청과 인증 정보 요청을 @RestController로 작성한다.
package com.ase.serverckecklist.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/")
    public String index() {
        return "This is Homepage";
    }

    @GetMapping("/auth")
    public Authentication auth() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
  1. Spring Security 작동 테스트를 위해 서버를 실행하고, 웹 브라우저에서 http://localhost:port로 접속하면 Spring Security에서 기본적으로 설정된 로그인 화면이 뜬다.

spring_security_default 1.png